package com.example.test.分布式锁的实现;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.example.test.主方法运行测试.time;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Description 单机版redis锁
 * @Author FL
 * @Date 16:30 2021/8/31
 * @Param
 **/

@Component
public class RedisLock {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static String key = "lock";


    /**
     * @Description 获取锁
     * @Author FL
     * @Date 16:31 2021/8/31
     * @Param [startTime,time] 开始时间,有效时间 ms
     **/
    public String getLock(Long startTime,Long time) {
        String lockValue = RandomUtil.randomString(6);
        long endTime = startTime + time;
        while (System.currentTimeMillis() < endTime) {
            if (redisTemplate.opsForValue().setIfAbsent(key, lockValue, time, TimeUnit.MILLISECONDS)) {
                return lockValue;
            }
        }
        return "";
    }


    /**
     * @Description 释放锁
     * @Author FL
     * @Date 16:41 2021/8/31
     * @Param [lockValue,startTime,time] 锁的value, 开始时间 ms ,有效时长 ms
     **/
    public boolean releaseLock(String lockValue ,Long startTime,Long time){
        String value = redisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(value)) {
            return true;
        }
        if (lockValue.equals(value)) {
            redisTemplate.delete(key);
            return true;
        }
        return false;
    }

}
